<template>
  <!-- 最外层的大盒子 -->
  <div class="big-box">
    <div class="container">
      <div class="welcome">
        <div class="pinkbox">
          <div class="signin">
            <h1>sign in</h1>

            <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="more-padding">
<!--              <div v-if="!tenantEnabled" style="max-height: 40px"></div>-->
                <a-flex vertical style="width: 100%;padding: 0 10%;" justify="space-between">
      <el-form-item v-if="tenantEnabled" prop="tenantId">
                    <el-select v-model="loginForm.tenantId" filterable placeholder="请选择/输入公司名称">
                      <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName"
                                 :value="item.tenantId"></el-option>
                      <template #prefix>
                        <svg-icon class="el-input__icon input-icon" icon-class="company" />
                      </template>
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
                    <el-input v-model="loginForm.username" auto-complete="off" class="login-input" placeholder="账号"
                              size="large" type="text">
                      <template #prefix>
                        <svg-icon class="el-input__icon input-icon" icon-class="user" />
                      </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
                    <el-input v-model="loginForm.password" auto-complete="off" placeholder="密码" size="large"
                              type="password" @keyup.enter="handleLogin">
                      <template #prefix>
                        <svg-icon class="el-input__icon input-icon" icon-class="password" />
                      </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input
          v-model="loginForm.code"
                      auto-complete="off"
                      placeholder="验证码"
          size="large"
                      style="width: 60%"
          @keyup.enter="handleLogin"
        >
                      <template #prefix>
                        <svg-icon class="el-input__icon input-icon" icon-class="validCode" />
                      </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>
                  <div>
                    <el-checkbox v-model="loginForm.rememberMe" style="width: 20%">记住密码</el-checkbox>
                    <el-form-item class="ml-6" style="width: 55%; float: right">
                      <el-button circle title="微信登录" @click="doSocialLogin('wechat')">
          <svg-icon icon-class="wechat" />
        </el-button>
                      <el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
          <svg-icon icon-class="maxkey" />
        </el-button>
                      <el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
          <svg-icon icon-class="gitee" />
        </el-button>
      </el-form-item>
                  </div>
                  <el-form-item>
                    <el-button :loading="loading" class="button submit" size="large" type="primary"
                               @click.prevent="handleLogin">
                      <svg-icon class="mr-5" icon-class="login" />
                      <span v-if="!loading">登 录</span>
                      <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
                </a-flex>
    </el-form>
          </div>
        </div>
        <div class="rightbox">
          <h2 class="title"><span>RY-Template</span>&<br />后台管理系统</h2>
          <p class="desc"> 通用 <span>前端</span></p>
          <img alt="RY-Template" class="flower" src="@/assets/logo/logo.png" />
          <br /><br />
          <p class="account">没有帐号？</p>
          <el-button v-if="register" class="button" style="padding: 8px 12px">
            <svg-icon class="mr-5" icon-class="register" />
            <router-link :to="'/register'">立即注册</router-link>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.big-box {
  //display: flex;
  /* 溢出隐藏 */
  height: 100vh;
  overflow-x: hidden;
  background: url('@/assets/images/bg.png') no-repeat center center;
  background-size: cover;
}

@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400|Lora');

/* div box styling */
.container {
  margin: auto;
  width: 650px;
  height: 550px;
  position: relative;
}

.welcome {
  background: #f6f6f6;
  width: 650px;
  height: 415px;
  position: absolute;
  top: 25%;
  border-radius: 5px;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1);
}

.pinkbox {
  position: absolute;
  top: -10%;
  left: 5%;
  background: #eac7cc;
  width: 320px;
  height: 500px;
  border-radius: 5px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  transition: all 0.5s ease-in-out;
  z-index: 2;
}

.nodisplay {
  display: none;
  transition: all 0.5s ease;
}

.leftbox,
.rightbox {
  position: absolute;
  width: 50%;
  transition: 1s all ease;
}

.leftbox {
  left: -2%;
}

.rightbox {
  right: -2%;
}

/* font & button styling */
h1 {
  font-family: 'Open Sans', sans-serif;
  text-align: center;
  margin-top: 65px;
  text-transform: uppercase;
  color: #f6f6f6;
  font-size: 2em;
  letter-spacing: 8px;
}

  .title {
  font-family: 'Lora', serif;
  color: #8e9aaf;
  font-size: 1.8em;
  line-height: 1.1em;
  letter-spacing: 3px;
  text-align: center;
  font-weight: 300;
  margin-top: 20%;
  margin-bottom: 20px;
}

.desc {
  margin-top: -8px;
}

.account {
  margin-top: 35%;
  font-size: 10px;
}

p {
  font-family: 'Open Sans', sans-serif;
  font-size: 0.7em;
  letter-spacing: 2px;
  color: #8e9aaf;
    text-align: center;
}

span {
  color: #eac7cc;
}

.flower {
  position: absolute;
  width: 120px;
  height: 120px;
  top: 45%;
  left: 29%;
  opacity: 0.7;
}

.smaller {
  width: 90px;
  height: 100px;
  top: 48%;
  left: 38%;
  opacity: 0.9;
}

button {
  padding: 12px;
  font-family: 'Open Sans', sans-serif;
  text-transform: uppercase;
  letter-spacing: 3px;
  font-size: 11px;
  border-radius: 10px;
  margin: auto;
  outline: none;
  display: block;
}

button:hover {
  background: #eac7cc;
  color: #f6f6f6;
  transition: background-color 1s ease-out;
  }

.button {
  //margin-top: 3%;
  background: #f6f6f6;
  color: #ce7d88;
  border: solid 1px #eac7cc;
}

.more-padding {
  padding-top: 35px;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.more-padding input {
  padding: 12px;
}

.more-padding .submit {
  //margin-top: 30px;
  }

.submit {
  //margin-top: 25px;
  padding: 12px;
  border-color: #ce7d88;
}

.submit:hover {
  background: #cbc0d3;
  border-color: #bfb1c9;
}

  .el-input {
  background: #eac7cc;
  width: 100%;
    height: 40px;
  color: #ce7d88;
  border: none;
  border-bottom: 1px solid rgba(246, 246, 246, 0.5);
}

.el-input::placeholder {
  color: #f6f6f6;
  letter-spacing: 2px;
  font-size: 1.3em;
  font-weight: 100;
}

.el-input:focus {
  color: #ce7d88;
  outline: none;
  border-bottom: 1.2px solid rgba(206, 125, 136, 0.7);
  font-size: 1em;
  transition: 0.8s all ease;
}

.el-input:focus::placeholder {
  opacity: 0;
    }

label {
  font-family: 'Open Sans', sans-serif;
  color: #ce7d88;
  font-size: 0.8em;
  letter-spacing: 1px;
  }

.checkbox {
  display: inline;
  white-space: nowrap;
  position: relative;
  left: -62px;
  top: 5px;
  }

.el-input[type='checkbox'] {
  width: 7px;
  background: #ce7d88;
}

.checkbox .el-input[type='checkbox']:checked + label {
  color: #ce7d88;
  transition: 0.5s all ease;
}

.login-code {
  width: 40%;
  height: 40px;
  float: right;

  img {
    width: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
